package cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;

public class Work23 {
    public static void main(String[] args) {
        //copyFile(new File("c:/MyDel.java"),new File("c://Yes.java"));
        //copyFileTo(new File("c:/MyDel.java"),new File("c://student/code"));
        //copyDir(new File("c:/t1"),new File("c:/ttt/t2"));
        //copyDirTo(new File("c:/t1"), new File("c:/ttt/t2"));

        System.out.println(isSame("c:/x.jpg", "c:/abc.zip"));
    }

    public static boolean isSame(String src, String dst) {
        return isSame(new File(src), new File(dst));
    }

    public static void copyFile(File src, File dst) {
        try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst)) {
            byte[] buf = new byte[10240];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
        } catch (Exception e) {

        }
    }

    public static boolean isSame(File a, File b) {
        boolean f = false;
        if (a.length() == b.length()) {
            try (FileInputStream is1 = new FileInputStream(a);
                 FileInputStream is2 = new FileInputStream(b)) {
                Random rand = new Random();
                int num = 0;
                while (is1.read() == is2.read() && is1.read() != -1 || is2.read() != -1) {
                    int sk = rand.nextInt(10240, 10240000);
                    is1.skip(sk);
                    is2.skip(sk);
                    ++num;
                }
                System.out.println(num);
                if (is2.read() == -1 && is1.read() == -1) {
                    f = true;
                }
            } catch (Exception e) {
            }
        }
        return f;
    }

    public static void copyFileTo(File src, File path) {
        if (!path.isDirectory()) {
            path.mkdirs();
        }
        copyFile(src, new File(path, src.getName()));
    }

    public static void copyDirTo(File src, File dst) {
        copyDir(src, new File(dst.getAbsoluteFile() + "/" + src.getName()));
    }

    public static void copyDir(File src, File dst) {
        File[] fs = src.listFiles();
        if (!dst.exists()) {
            dst.mkdirs();
        }
        for (File f : fs) {
            if (f.isDirectory()) {
                copyDir(f, new File(dst.getAbsoluteFile() + "/" + f.getName()));
            } else if (f.isFile()) {
                copyFileTo(f, dst);
            }
        }
    }
}
